﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Air_condition.DO;
using Air_condition.BU;
using Com.BU;
using Com.DA;
using System.Text.RegularExpressions;
using System.Media;
using Air_condition.Reference_Path;
using System.Windows.Controls.Primitives;
using System.Xml;
using System.Reflection;

namespace Air_condition.GUI
{
    /// <summary>
    /// Interaction logic for ucAirConditioning.xaml
    /// </summary>
    public partial class ucAirConditioning : UserControl
    {
        // Declare variables
        public AlternativeManager altman = new AlternativeManager();
        TemplateManager temman = new TemplateManager();
        Alternative alt = new Alternative();
        Room room = new Room();
        Equip equip;
        Wall wall;
        Roof roof;
        TabItem tabitem = new TabItem();

        double dbOutsideTemperature;
        string key = "";
        int iEquipment = 1;
        int iWall = 1;
        int iRoof = 1;
        int iRoom = 1;
        bool ceilling = true;
        bool blroof = true;
        bool floor = true;
        bool bSelectedCeiling = true;

        // DELEGATE Add Room
        public delegate void AddRoom(Room r, bool update);
        public AddRoom MyRoom;

        // DELEGATE Delete Room
        public delegate void DeleteRoom();
        public DeleteRoom DelRoom;

        #region LOAD
        public ucAirConditioning()
        {
            InitializeComponent();
            // Load data on interface
            LoadSpace();
            LoadEquipment();
            LoadTypeOfGlass();
            LoadGlassDirection();
            LoadCeilling();
            LoadCeillingLayer();
            LoadWall();
            LoadRoofSurface();
            LoadStructureRoof();
            LoadCharacteristicRoof();
            LoadStructureFloor();
            LoadCharacteristicFloor();
            setData();
        }

        /// <summary>
        /// Method load templates
        /// </summary>
        /// <param name="o">object room to load template</param>
        public void LoadTemplate(object o)
        {
            temman = (TemplateManager)o;

            if (temman.lroom.Count != 0)
            {
                cbxTemplateRoom.ItemsSource = temman.lroom;
                cbxTemplateRoom.DisplayMemberPath = "sName";
            }

            if (temman.linternalload.Count != 0)
            {
                cbxTemplateInternalLoad.ItemsSource = temman.linternalload;
                cbxTemplateInternalLoad.DisplayMemberPath = "sName";
            }

            if (temman.lglass.Count != 0)
            {
                cbxTemplateConstruction.ItemsSource = temman.lglass;
                cbxTemplateConstruction.DisplayMemberPath = "sName";
            }
        }

        /// <summary>
        /// Set data for comboboxes
        /// </summary>
        public void setData()
        {
            // combobox Gender
            cbxGender.Items.Add("Male");
            cbxGender.Items.Add("Female");
            cbxGender.Items.Add("Child");
            cbxGender.SelectedIndex = -1;

            //  combobox Frame
            cbxTypeOfFrameGlass.Items.Add("Wood frame");
            cbxTypeOfFrameGlass.Items.Add("Metal frame");
            cbxTypeOfFrameGlass.SelectedIndex = -1;

            //  combobox Latitue
            cbxLatitute.Items.Add("10 deg North");
            cbxLatitute.Items.Add("20 deg North");
            cbxLatitute.Items.Add("30 deg North");

            //  combobox Solar Hour
            for (int i = 6; i <= 17; i++)
            {
                cbxSolarHour.Items.Add(i);
            }

            //  combobox Month
            for (int i = 1; i <= 12; i++)
            {
                cbxMonth.Items.Add(i);
            }

            //  combobox Time
            for (int i = 1; i <= 24; i++)
            {
                cbxTime.Items.Add(i);
            }

            //  combobox Pressure
            cbxPressure.Items.Add(150);
            cbxPressure.Items.Add(500);
            cbxPressure.Items.Add(700);

            // combobox Color
            cbxColor.Items.Add("Dark Color");
            cbxColor.Items.Add("Light Color");
            cbxColor.Items.Add("Average Color");
            cbxColor.SelectedIndex = -1;

            // combobox Exposure
            cbxTypeOfExposure.Items.Add("Outside Air");
            cbxTypeOfExposure.Items.Add("The space without air codition");
            cbxTypeOfExposure.Items.Add("The air codition space");
            cbxTypeOfExposure.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Coditioning Space
        /// </summary>
        public void LoadSpace()
        {
            cbxSpaceConditioning.ItemsSource = null;
            cbxSpaceConditioning.Items.Clear();
            cbxSpaceConditioning.ItemsSource = LibraryManagerInCom.AirConditionPlaceList;
            cbxSpaceConditioning.DisplayMemberPath = "description";
            cbxSpaceConditioning.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Type of Equipment
        /// </summary>
        public void LoadEquipment()
        {
            cbxTypeOfEquipment.ItemsSource = null;
            cbxTypeOfEquipment.Items.Clear();
            cbxTypeOfEquipment.ItemsSource = LibraryManagerInCom.EquipmentList;
            cbxTypeOfEquipment.DisplayMemberPath = "equipment_name";
            cbxTypeOfEquipment.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Type of Glass
        /// </summary>
        public void LoadTypeOfGlass()
        {
            cbxTypeOfGlass.ItemsSource = null;
            cbxTypeOfGlass.Items.Clear();
            cbxTypeOfGlass.ItemsSource = LibraryManagerInCom.GlassCoeffientList;
            cbxTypeOfGlass.DisplayMemberPath = "glass_type";
            cbxTypeOfGlass.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Direction
        /// </summary>
        public void LoadGlassDirection()
        {
            cbxDirection.ItemsSource = null;
            cbxDirection.Items.Clear();
            cbxDirection.ItemsSource = LibraryManagerInCom.GlassDirectionList;
            cbxDirection.DisplayMemberPath = "glass_direction";
            cbxDirection.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Type of Wall
        /// </summary>
        public void LoadWall()
        {
            cbxTypeofWall.ItemsSource = null;
            cbxTypeofWall.Items.Clear();
            cbxTypeofWall.ItemsSource = LibraryManagerInCom.WallMaterialList;
            cbxTypeofWall.DisplayMemberPath = "description";
        }

        /// <summary>
        /// Load data for combobox Structure of Ceilling
        /// </summary>
        public void LoadCeilling()
        {
            cbxStructureOfCeilling.ItemsSource = null;
            cbxStructureOfCeilling.Items.Clear();
            cbxStructureOfCeilling.ItemsSource = LibraryManagerInCom.CeilingList;
            cbxStructureOfCeilling.DisplayMemberPath = "description";
            cbxStructureOfCeilling.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Characteristics Of Ceilling
        /// </summary>
        public void LoadCeillingLayer()
        {
            cbxCharacteristicsOfCeilling.ItemsSource = null;
            cbxCharacteristicsOfCeilling.Items.Clear();
            cbxCharacteristicsOfCeilling.ItemsSource = LibraryManagerInCom.CeilingLayerList;
            cbxCharacteristicsOfCeilling.DisplayMemberPath = "layer_type";
            cbxCharacteristicsOfCeilling.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Structure of Floor
        /// </summary>
        public void LoadStructureFloor()
        {
            cbxStructureOfFloor.ItemsSource = null;
            cbxStructureOfFloor.Items.Clear();
            cbxStructureOfFloor.ItemsSource = LibraryManagerInCom.CeilingList;
            cbxStructureOfFloor.DisplayMemberPath = "description";
            cbxStructureOfFloor.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Characteristics Of Floor
        /// </summary>
        public void LoadCharacteristicFloor()
        {
            cbxCharacteristicsOfFloor.ItemsSource = null;
            cbxCharacteristicsOfFloor.Items.Clear();
            cbxCharacteristicsOfFloor.ItemsSource = LibraryManagerInCom.CeilingLayerList;
            cbxCharacteristicsOfFloor.DisplayMemberPath = "layer_type";
            cbxCharacteristicsOfFloor.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Structure of Roof
        /// </summary>
        public void LoadStructureRoof()
        {
            cbxStructureOfRoof.ItemsSource = null;
            cbxStructureOfRoof.Items.Clear();
            cbxStructureOfRoof.ItemsSource = LibraryManagerInCom.RoofCeilingStructureList;
            cbxStructureOfRoof.DisplayMemberPath = "roof_ceiling_structure";
            cbxStructureOfRoof.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Characteristic of Roof
        /// </summary>
        public void LoadCharacteristicRoof()
        {
            cbxCharacteristicsOfRoof.ItemsSource = null;
            cbxCharacteristicsOfRoof.Items.Clear();
            cbxCharacteristicsOfRoof.ItemsSource = LibraryManagerInCom.RoofCeilingCharacteristicList;
            cbxCharacteristicsOfRoof.DisplayMemberPath = "roof_ceiling_characteristic";
            cbxCharacteristicsOfRoof.SelectedIndex = -1;
        }

        /// <summary>
        /// Load data for combobox Type of roof surface
        /// </summary>
        public void LoadRoofSurface()
        {
            cbxTypeOfSurface.ItemsSource = null;
            cbxTypeOfSurface.Items.Clear();
            cbxTypeOfSurface.ItemsSource = LibraryManagerInCom.RoofSurfaceList;
            cbxTypeOfSurface.DisplayMemberPath = "surface_roof";
            cbxTypeOfSurface.SelectedIndex = -1;
        }
        #endregion

        #region ROOM
        // PROCESS TAB ROOM

        private void cbxTemplateRoom_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTemplateRoom.SelectedItem != null)
            {
                Room ro = ((Room)cbxTemplateRoom.SelectedItem);
                if (ro != null)
                {
                    txtWidthRoom.Text = ro.dbWidth.ToString();
                    txtHeighRoom.Text = ro.dbHeigh.ToString();
                    txtLengthRoom.Text = ro.dbLength.ToString();
                    txtOutsideTemperature.Text = ro.dbOutSideTemperature.ToString();
                    txtInsideTemperature.Text = ro.dbInsideTemperature.ToString();
                    txtOutsideAirContainingLevel.Text = ro.dbOutsideAirContainingLevel.ToString();
                    txtInsideAirContainingLevel.Text = ro.dbInsideAirContainingLevel.ToString();
                }
            }
        }

        private void txtInsideTemperature_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtInsideTemperature);
            CheckManHeat();
            btnApplyRoom.IsEnabled = true;
        }

        /// <summary>
        /// Display outside temperature to interface
        /// </summary>
        /// <param name="sOutsideTemperature">outside teperature</param>
        public void SetOutsideTemperature(string sOutsideTemperature)
        {
            txtOutsideTemperature.Text = sOutsideTemperature;
            dbOutsideTemperature = Convert.ToDouble(sOutsideTemperature);
        }

        /// <summary>
        /// Set Enable/Desible Tab Room
        /// </summary>
        /// <param name="b">Enable(true)/Desible(false)</param>
        public void EnableRoom(bool b)
        {
            tabiInternalLoad.IsEnabled = b;
            tabConstruction.IsEnabled = b;
            btnCopyRoom.IsEnabled = b;
            btnDeleteRoom.IsEnabled = b;
            CanvasRoom.IsEnabled = b;
        }

        /// <summary>
        /// Add Room or Update Room to list
        /// </summary>
        /// <param name="o">Room object</param>
        public void addRoom(object o)
        {
            Room r = (Room)o;
            bool overload = false;
            if (r.sName == null || r.sName == "Default")
            {
                if (txtName.Text != "")
                {
                    foreach (Room ro in alt.lRoom)
                    {
                        if (txtName.Text == ro.sName)
                        {
                            r.sName = "Room " + iRoom;
                            overload = true;
                        }
                    }
                    if (!overload)
                    {
                        r.sName = txtName.Text;
                    }
                }
                else
                {
                    r.sName = "Room " + iRoom;
                }
            }
            CheckRoomName(r);
            alt.lRoom.Add(r);
            iRoom++;
            if (MyRoom != null)
            {
                MyRoom(r, false);
            }
        }

        public void CheckRoomName(Room r)
        {
            foreach (Room ro in alt.lRoom)
            {
                if (r.sName == ro.sName)
                {
                    iRoom++;
                    r.sName = "Room " + iRoom;
                    CheckRoomName(r);
                }
            }
        }

        /// <summary>
        /// Load information of Room when choosing room in tree view
        /// </summary>
        /// <param name="ro">Room object</param>
        public void loadRoom(Room ro)
        {
            room = ro;
            if (room != null)
            {
                EnableRoom(true);

                // load tab room
                txtName.Text = room.sName;
                txtWidthRoom.Text = room.dbWidth.ToString();
                txtHeighRoom.Text = room.dbHeigh.ToString();
                txtLengthRoom.Text = room.dbLength.ToString();
                txtOutsideTemperature.Text = room.dbOutSideTemperature.ToString();
                txtInsideTemperature.Text = room.dbInsideTemperature.ToString();
                txtOutsideAirContainingLevel.Text = room.dbOutsideAirContainingLevel.ToString();
                txtInsideAirContainingLevel.Text = room.dbInsideAirContainingLevel.ToString();

                // load tab internal
                cbxSpaceConditioning.SelectedIndex = room.inter.iSpaceConditioning;
                txtPeopleDensity.Text = room.inter.dbDensityPeople.ToString();
                cbxGender.SelectedIndex = room.inter.iGender;
                txtPeopleLatentHeat.Text = room.inter.dbLatentHeat.ToString();
                txtPeopleSensibleHeat.Text = room.inter.dbSensibleHeat.ToString();
                txtAmountAir.Text = room.inter.dbAirMountForOnePeople.ToString();
                LoadEquipList();

                // load tab construction
                cbxTypeOfFrameGlass.SelectedIndex = room.gl.iWindowFrameType;
                txtAreaOfDoor.Text = room.gl.dbArea.ToString();
                cbxTypeOfGlass.SelectedIndex = room.gl.iTypeofglass;
                txtCoefficientOfGlass.Text = room.gl.dbGlassCoefficient.ToString();
                cbxLatitute.SelectedIndex = room.gl.iLatitute;
                cbxSolarHour.SelectedIndex = room.gl.iSolarHour;
                cbxMonth.SelectedIndex = room.gl.iMonth;
                cbxDirection.SelectedIndex = room.gl.iDirection;
                cbxPressure.SelectedIndex = room.gl.iPressure;
                cbxTime.SelectedIndex = room.gl.iTime;
                txtSolarRadiation.Text = room.gl.dbSolarRadition.ToString();
                txtImmediate.Text = room.gl.dbImmediateCoefficient.ToString();

                lstWall.Items.Clear();
                lstRoof.Items.Clear();
                radRoof.IsChecked = false;
                radRoof.IsChecked = true;
                bool bCeiling = false;
                bool bFloor = false;
                foreach (Construction c in room.lConstruction)
                {
                    if (c is Ceiling)
                    {
                        txtWidthOfCeilling.Text = c.dbWidth.ToString();
                        txtLengthOfCeilling.Text = c.dbLength.ToString();
                        cbxStructureOfCeilling.SelectedIndex = c.iStructure;
                        cbxCharacteristicsOfCeilling.SelectedIndex = c.iCharacteristics;
                        txtHeatTransfer.Text = c.dbHeatTransferCoefficient.ToString();
                        radCeilling.IsChecked = true;
                        bCeiling = true;
                    }
                    else
                    {
                        if (c is Roof)
                        {
                            lstRoof.Items.Add(c);
                            radRoof.IsChecked = false;
                            radRoof.IsChecked = true;
                        }
                        else
                        {
                            if (c is Wall)
                            {
                                lstWall.Items.Add(c);
                            }
                            else
                            {
                                if (c is Floor)
                                {
                                    txtWidthOfFloor.Text = c.dbWidth.ToString();
                                    txtLengthOfFloor.Text = c.dbLength.ToString();
                                    cbxStructureOfFloor.SelectedIndex = c.iStructure;
                                    cbxCharacteristicsOfFloor.SelectedIndex = c.iCharacteristics;
                                    txtHeatTransferOfFloor.Text = c.dbHeatTransferCoefficient.ToString();
                                    bFloor = true;
                                }
                            }
                        }
                    }
                }
                if (!bCeiling)
                {
                    txtWidthOfCeilling.Text = "0";
                    txtLengthOfCeilling.Text = "0";
                    cbxStructureOfCeilling.SelectedIndex = -1;
                    cbxCharacteristicsOfCeilling.SelectedIndex = -1;
                    txtHeatTransfer.Text = "0";
                }
                if (!bFloor)
                {
                    txtWidthOfFloor.Text = "0";
                    txtLengthOfFloor.Text = "0";
                    cbxStructureOfFloor.SelectedIndex = -1;
                    cbxCharacteristicsOfFloor.SelectedIndex = -1;
                    txtHeatTransferOfFloor.Text = "0";
                }
                if (lstWall.Items.Count != 0)
                {
                    EnableWall(true);
                }
                else
                {
                    EnableWall(false);
                }
                if (lstRoof.Items.Count != 0)
                {
                    enableroof(true);
                }
                else
                {
                    enableroof(false);
                }
            }
        }

        // Process buttons on Room Tab
        private void btnApplyRoom_Click(object sender, RoutedEventArgs e)
        {
            ApplyRoom();
        }

        public void ApplyRoom()
        {
            btnApplyRoom.IsEnabled = false;
            bool overload = false;
            foreach (Room ro in alt.lRoom)
            {
                if (txtName.Text == ro.sName && txtName.Text != room.sName)
                {
                    MessageBox.Show("Room was existed");
                    txtName.Text = room.sName;
                    overload = true;
                }
            }

            if (!overload)
            {
                room.sName = txtName.Text;
                room.dbOutSideTemperature = Convert.ToDouble(txtOutsideTemperature.Text);
                room.dbOutsideAirContainingLevel = Convert.ToDouble(txtOutsideAirContainingLevel.Text);
                room.dbInsideAirContainingLevel = Convert.ToDouble(txtInsideAirContainingLevel.Text);
                room.dbWidth = Convert.ToDouble(txtWidthRoom.Text);
                room.dbHeigh = Convert.ToDouble(txtHeighRoom.Text);
                room.dbLength = Convert.ToDouble(txtLengthRoom.Text);
                room.dbVolume = room.dbWidth * room.dbHeigh * room.dbLength;
                tb_exiting_air ea = null;
                if (room.dbVolume < 500)
                {
                    ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 400);
                }
                else
                {
                    if (room.dbVolume == 500)
                    {
                        ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 500);
                    }
                    else
                    {
                        if (room.dbVolume > 500 && room.dbVolume <= 1000)
                        {
                            ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 1000);
                        }
                        else
                        {
                            if (room.dbVolume > 1000 && room.dbVolume <= 2000)
                            {
                                ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 2000);
                            }
                            else
                            {
                                if (room.dbVolume > 2000 && room.dbVolume <= 2500)
                                {
                                    ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 2500);
                                }
                                else
                                {
                                    ea = (tb_exiting_air)LibraryManagerInCom.ExitAirList.SingleOrDefault(ex => ex.room_volume == 300);
                                }
                            }
                        }
                    }
                }

                if (ea != null)
                {
                    room.dbAirCoefficient = Convert.ToDouble(ea.coefficient);
                }
                room.dbInsideTemperature = Convert.ToDouble(txtInsideTemperature.Text);
                if (alt.lRoom.IndexOf(room) != -1)
                {
                    if (MyRoom != null)
                    {
                        MyRoom(room, true);
                    }
                    alt.lRoom[alt.lRoom.IndexOf(room)] = room;
                    btnApplyRoom.IsEnabled = false;
                }
            }
        }

        private void btnNewRoom_Click(object sender, RoutedEventArgs e)
        {
            Room r = new Room();
            r = (Room)temman.lroom[0].Clone();
            r.dbOutSideTemperature = dbOutsideTemperature;
            r.inter = (InternalLoad)temman.linternalload[0].Clone();
            r.gl = (Glass)temman.lglass[0].Clone();
            r.lConstruction.Add(temman.lceiling[0]);
            r.lConstruction.Add(temman.lfloor[0]);
            Wall w = (Wall)temman.lwall[0].Clone();
            w.sName = "Wall 1";
            r.lConstruction.Add(w);
            addRoom(r);
        }

        private void btnDeleteRoom_Click(object sender, RoutedEventArgs e)
        {
            alt.lRoom.Remove(room);
            if (DelRoom != null)
            {
                DelRoom();
            }
            if (alt.lRoom.Count == 0)
            {
                iRoom = 1;
                EnableRoom(false);
            }
            txtName.Text = "";
        }

        private void btnCopyRoom_Click(object sender, RoutedEventArgs e)
        {
            if (room != null)
            {
                Room copyroom = (Room)room.Clone();
                addRoom(copyroom);
            }
        }

        #endregion

        #region INTERNALOAD
        // XỬ LÝ TAB INTERNAL LOAD

        private void cbxTemplateInternalLoad_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTemplateInternalLoad.SelectedItem != null)
            {
                InternalLoad oin = (InternalLoad)cbxTemplateInternalLoad.SelectedItem;
                if (oin != null)
                {
                    cbxSpaceConditioning.SelectedIndex = oin.iSpaceConditioning;
                    txtPeopleDensity.Text = oin.dbDensityPeople.ToString();
                    cbxGender.SelectedIndex = oin.iGender;
                    txtAmountAir.Text = oin.dbAirMountForOnePeople.ToString();
                    EnableEquipment(true);
                    Equip equip = oin.lequip[0];
                    iEquipment = 1;
                    equip.sName = "Equipment " + iEquipment;
                    iEquipment++;
                    room.inter.lequip.Clear();
                    room.inter.lequip.Add(equip);
                    //LoadEquipList();
                    lstEquipment.SelectedIndex = 0;
                }
            }
        }

        private void cbxSpaceConditioning_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxSpaceConditioning.SelectedItem != null)
            {
                tb_air_conditioning_place conplace = (tb_air_conditioning_place)cbxSpaceConditioning.SelectedItem;
                if (conplace != null)
                {
                    txtPeopleDensity.Text = conplace.people_density.ToString();
                    txtAmountAir.Text = conplace.air_amount_per_perople.ToString();
                    CheckManHeat();
                    btnApplyInternalLoad.IsEnabled = true;
                }
            }
        }

        private void cbxGender_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxGender.SelectedItem != null)
            {
                CheckManHeat();
                btnApplyInternalLoad.IsEnabled = true;
            }
        }

        private void lstEquipment_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lstEquipment.SelectedItem != null)
            {
                equip = (Equip)lstEquipment.SelectedItem;
                if (equip != null)
                {
                    txtEquipment.Text = equip.sName;
                    cbxTypeOfEquipment.SelectedIndex = equip.iType;
                    txtEnergytOfEquipment.Text = equip.dbEnergy.ToString();
                }
            }
        }

        private void lstEquipment_GotFocus(object sender, RoutedEventArgs e)
        {
            SaveEquip();
        }

        private void cbxTypeOfEquipment_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTypeOfEquipment.SelectedItem != null)
            {
                tb_equipment equipment = (tb_equipment)cbxTypeOfEquipment.SelectedItem;
                if (equipment != null)
                {
                    txtEnergytOfEquipment.Text = equipment.energy.ToString();
                    btnApplyInternalLoad.IsEnabled = true;
                }
            }
        }

        /// <summary>
        /// Check Man Heat when changing parameter on interface
        /// </summary>
        public void CheckManHeat()
        {
            if (cbxSpaceConditioning != null && cbxGender != null)
            {
                if (cbxSpaceConditioning.SelectedItem != null && cbxGender.SelectedItem != null)
                {
                    double dbInsideTemperature = Convert.ToDouble(txtInsideTemperature.Text);
                    tb_air_conditioning_place conplace = (tb_air_conditioning_place)cbxSpaceConditioning.SelectedItem;
                    tb_heat_by_man manheat = LibraryManagerInCom.HeatByManList.SingleOrDefault(mh => mh.working_place_id == conplace.id && mh.working_place_temperature == dbInsideTemperature);
                    if (manheat != null)
                    {
                        if (cbxGender.SelectedItem.ToString() == "Male")
                        {
                            txtPeopleLatentHeat.Text = manheat.latent_heat.ToString();
                            txtPeopleSensibleHeat.Text = manheat.sensible_heat.ToString();
                        }
                        else
                        {
                            if (cbxGender.SelectedItem.ToString() == "Female")
                            {
                                txtPeopleLatentHeat.Text = (manheat.latent_heat * 0.85).ToString();
                                txtPeopleSensibleHeat.Text = (manheat.sensible_heat * 0.85).ToString();
                            }
                            else
                            {
                                txtPeopleLatentHeat.Text = (manheat.latent_heat * 0.75).ToString();
                                txtPeopleSensibleHeat.Text = (manheat.sensible_heat * 0.75).ToString();
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Enable/Desible interface Equipment
        /// </summary>
        /// <param name="b">Enable(true)/Desible(false)</param>
        public void EnableEquipment(bool b)
        {
            txtEquipment.IsEnabled = b;
            cbxTypeOfEquipment.IsEnabled = b;
            lstEquipment.IsEnabled = b;
            txtEnergytOfEquipment.IsEnabled = b;
            btnCopyEquip.IsEnabled = b;
            btnDeleteEquip.IsEnabled = b;
        }

        /// <summary>
        /// Add an equipment object to list equipment
        /// </summary>
        /// <param name="o">equipment object</param>
        public void addEquip(object o)
        {
            Equip equip = (Equip)o;
            bool overload = false;
            if (txtEquipment.Text != "")
            {
                foreach (Equip e in room.inter.lequip)
                {
                    if (e.sName == txtEquipment.Text)
                    {
                        overload = true;
                        equip.sName = "Equipment " + iEquipment;
                        break;
                    }
                }
                if (!overload)
                {
                    equip.sName = txtEquipment.Text;
                }

            }
            else
            {
                equip.sName = "Equipment " + iEquipment;
            }
            CheckEquipName(equip);
            iEquipment++;
            room.inter.lequip.Add(equip);
        }

        public void CheckEquipName(Equip e)
        {
            foreach (Equip eq in room.inter.lequip)
            {
                if (e.sName == eq.sName)
                {
                    iEquipment++;
                    e.sName = "Equipment " + iEquipment;
                    CheckEquipName(e);
                }
            }
        }

        /// <summary>
        /// Load data for combobox Equipment
        /// </summary>
        public void LoadEquipList()
        {
            lstEquipment.ItemsSource = null;
            lstEquipment.ItemsSource = room.inter.lequip;
            lstEquipment.DisplayMemberPath = "sName";
        }

        public void SaveEquip()
        {
            if (equip != null)
            {
                bool overload = false;
                foreach (Equip eq in room.inter.lequip)
                {
                    if (txtEquipment.Text == eq.sName && txtEquipment.Text != equip.sName)
                    {
                        MessageBox.Show("Equipment was existed");
                        txtEquipment.Text = equip.sName;
                        overload = true;
                    }
                }
                if (!overload)
                {
                    if (txtEquipment.Text != "")
                    {
                        equip.sName = txtEquipment.Text;
                    }
                    equip.iType = cbxTypeOfEquipment.SelectedIndex;
                    equip.dbEnergy = Convert.ToDouble(txtEnergytOfEquipment.Text);
                }
            }
        }

        // Process buttons on Internal Load Tab
        private void btnApplyInternalLoad_Click(object sender, RoutedEventArgs e)
        {
            ApplyInternalLoad();
        }

        public void ApplyInternalLoad()
        {
            btnApplyInternalLoad.IsEnabled = false;
            room.inter.dbDensityPeople = Convert.ToDouble(txtPeopleDensity.Text);
            room.inter.iSpaceConditioning = cbxSpaceConditioning.SelectedIndex;
            room.inter.iGender = cbxGender.SelectedIndex;
            room.inter.dbLatentHeat = Convert.ToDouble(txtPeopleLatentHeat.Text);
            room.inter.dbSensibleHeat = Convert.ToDouble(txtPeopleSensibleHeat.Text);
            room.inter.dbAirMountForOnePeople = Convert.ToDouble(txtAmountAir.Text);
            SaveEquip();
            LoadEquipList();
        }

        private void btnEquip_Click(object sender, RoutedEventArgs e)
        {
            EnableEquipment(true);
            Equip equip = new Equip();
            addEquip(equip);
        }

        private void btnDeleteLoad_Click(object sender, RoutedEventArgs e)
        {
            room.inter.lequip.Remove(equip);
            if (lstEquipment.Items.Count == 0)
            {
                EnableEquipment(false);
                iEquipment = 1;
            }
        }

        private void btnCopyEquip_Click(object sender, RoutedEventArgs e)
        {
            if (equip != null)
            {
                Equip equipment = (Equip)equip.Clone();
                addEquip(equipment);
            }
        }

        #endregion

        #region CONSTRUCTION

        private void cbxTemplateConstruction_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTemplateConstruction.SelectedItem != null)
            {
                Glass glass = (Glass)cbxTemplateConstruction.SelectedItem;
                Floor floor = new Floor();
                Roof roof = new Roof();
                Ceiling cei = new Ceiling();
                Wall wall = new Wall();
                roof = null;
                cei = null;
                if (glass != null)
                {
                    string name = glass.sName;
                    roof = temman.lroof.SingleOrDefault(rf => rf.sName.Trim().Equals(name));
                    if (roof != null)
                    {
                        roof = (Roof)roof.Clone();
                    }
                    cei = temman.lceiling.SingleOrDefault(rk => rk.sName.Trim().Equals(name));
                    wall = (Wall)temman.lwall.SingleOrDefault(rf => rf.sName.Trim().Equals(name)).Clone();
                    floor = temman.lfloor.SingleOrDefault(rf => rf.sName.Trim().Equals(name));

                    cbxTypeOfFrameGlass.SelectedIndex = glass.iWindowFrameType;
                    txtAreaOfDoor.Text = glass.dbArea.ToString();
                    cbxTypeOfGlass.SelectedIndex = glass.iTypeofglass;
                    txtCoefficientOfGlass.Text = glass.dbGlassCoefficient.ToString();
                    cbxLatitute.SelectedIndex = glass.iLatitute;
                    cbxSolarHour.SelectedIndex = glass.iSolarHour;
                    cbxMonth.SelectedIndex = glass.iMonth;
                    cbxPressure.SelectedIndex = glass.iPressure;
                    cbxTime.SelectedIndex = glass.iTime;
                    txtSolarRadiation.Text = glass.dbSolarRadition.ToString();
                    cbxDirection.SelectedIndex = glass.iDirection;
                    txtImmediate.Text = glass.dbImmediateCoefficient.ToString();

                    if (cei != null)
                    {
                        //   hien doi tuong Ceiling 
                        radCeilling.IsChecked = false;
                        radCeilling.IsChecked = true;
                        txtLengthOfCeilling.Text = cei.dbLength.ToString();
                        txtWidthOfCeilling.Text = cei.dbWidth.ToString();
                        cbxCharacteristicsOfCeilling.SelectedIndex = cei.iCharacteristics;
                        cbxStructureOfCeilling.SelectedIndex = cei.iStructure;
                        txtHeatTransfer.Text = cei.dbHeatTransferCoefficient.ToString();
                    }
                    else
                    {
                        //  hien doi tuong roof
                        radRoof.IsChecked = false;
                        radRoof.IsChecked = true;
                        iRoof = 1;
                        roof.sname = "Roof " + iRoof;
                        iRoof++;
                        room.lConstruction.RemoveAll(c => c is Roof);
                        room.lConstruction.Add(roof);
                        enableroof(true);
                        lstRoof.Items.Clear();
                        lstRoof.Items.Add(roof);
                        lstRoof.DisplayMemberPath = "sName";
                        lstRoof.SelectedIndex = 0;
                    }

                    iWall = 1;
                    wall.sname = "Wall " + iWall;
                    iWall++;
                    room.lConstruction.RemoveAll(c => c is Wall);
                    room.lConstruction.Add(wall);
                    EnableWall(true);
                    lstWall.Items.Clear();
                    lstWall.Items.Add(wall);
                    lstWall.DisplayMemberPath = "sName";
                    lstWall.SelectedIndex = 0;

                    //  hien doi tuong floor
                    txtWidthOfFloor.Text = floor.dbWidth.ToString();
                    txtLengthOfFloor.Text = floor.dbLength.ToString();
                    cbxCharacteristicsOfFloor.SelectedIndex = floor.iCharacteristics;
                    cbxStructureOfFloor.SelectedIndex = floor.iStructure;
                    txtHeatTransferOfFloor.Text = floor.dbHeatTransferCoefficient.ToString();
                }
            }
        }

        // Load hệ số truyền nhiệt của ceiling
        private void cbxStructureOfCeilling_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxStructureOfCeilling.SelectedItem != null)
            {
                if (ceilling)
                {
                    LoadCeillingLayer();
                    ceilling = false;
                }
                loadCeilling();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxCharacteristicsOfCeilling_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxCharacteristicsOfCeilling.SelectedItem != null)
            {
                loadCeilling();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void loadCeilling()
        {
            if (cbxStructureOfCeilling.SelectedIndex != -1 && cbxCharacteristicsOfCeilling.SelectedIndex != -1)
            {
                tb_ceiling ce = (tb_ceiling)cbxStructureOfCeilling.SelectedItem;
                tb_ceiling_layer l = (tb_ceiling_layer)cbxCharacteristicsOfCeilling.SelectedItem;
                tb_heat_transfer_ceiling tr = LibraryManagerInCom.CeilingCoefficientList.SingleOrDefault(c => c.ceiling_id == ce.id && c.layer_id == l.id);

                if (tr != null)
                {
                    txtHeatTransfer.Text = tr.coefficient.ToString();
                }
            }

        }

        //  Load hệ số truyền nhiệt của sàn
        private void cbxStructureOfFloor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxStructureOfFloor.SelectedItem != null)
            {
                if (floor)
                {
                    LoadCharacteristicFloor();
                    floor = false;
                }
                loadFloor();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxCharacteristicsOfFloor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxCharacteristicsOfFloor.SelectedItem != null)
            {
                loadFloor();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void loadFloor()
        {

            if (cbxStructureOfFloor.SelectedIndex != -1 && cbxCharacteristicsOfFloor.SelectedIndex != -1)
            {
                tb_ceiling floor = (tb_ceiling)cbxStructureOfFloor.SelectedItem;
                tb_ceiling_layer layerfloor = (tb_ceiling_layer)cbxCharacteristicsOfFloor.SelectedItem;
                tb_heat_transfer_ceiling tran = LibraryManagerInCom.CeilingCoefficientList.SingleOrDefault(c => c.ceiling_id == floor.id && c.layer_id == layerfloor.id);
                if (tran != null)
                {
                    txtHeatTransferOfFloor.Text = tran.coefficient.ToString();
                }
            }

        }

        //  Load hệ số truyền nhiệt của roof
        private void cbxStructureOfRoof_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxStructureOfRoof.SelectedItem != null)
            {
                if (blroof)
                {
                    LoadCharacteristicRoof();
                    blroof = false;
                }
                loadRoof();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxCharacteristicsOfRoof_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxCharacteristicsOfRoof.SelectedItem != null)
            {
                loadRoof();
                btnApplyConstruction.IsEnabled = true;
            }
        }
        private void loadRoof()
        {
            if (cbxStructureOfRoof.SelectedIndex != -1 && cbxCharacteristicsOfRoof.SelectedIndex != -1)
            {
                tb_roof_ceiling_structure structureroof = (tb_roof_ceiling_structure)cbxStructureOfRoof.SelectedItem;
                tb_roof_ceiling_characteristic characroof = (tb_roof_ceiling_characteristic)cbxCharacteristicsOfRoof.SelectedItem;
                tb_roof_ceiling_heat_coefficient ro = LibraryManagerInCom.RoofCeilingHeatList.SingleOrDefault(r => r.structure_id == structureroof.id && r.characteristic_id == characroof.id);
                if (ro != null)
                {
                    txtHeatTransferOfRoof.Text = ro.heat_coefficient.ToString();
                }
            }
        }

        private void cbxTypeOfSurface_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTypeOfSurface.SelectedItem != null)
            {
                txtAbsorptionCoefficient.Text = ((tb_roof_surface)cbxTypeOfSurface.SelectedItem).absorption_coefficient.ToString();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxTypeOfGlass_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTypeOfGlass.SelectedItem != null)
            {
                txtCoefficientOfGlass.Text = ((tb_radiation_characteristics)cbxTypeOfGlass.SelectedItem).glass_coefficient.ToString();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        //  Load Solar Radiation từ 4 combobox Latitute, Direction, Solar hour, Month đã được chọn

        private void loadSolarRadition()
        {
            if (cbxSolarHour.SelectedIndex != -1 && cbxDirection.SelectedIndex != -1 && cbxLatitute.SelectedIndex != -1 && cbxMonth.SelectedIndex != -1)
            {

                try
                {

                    int? strDirectioncbx = int.Parse(((tb_glass_direction)cbxDirection.SelectedItem).id.ToString());
                    int? strSolarHourcbx = (int)cbxSolarHour.SelectedItem;
                    int? strMonthcbx = (int)cbxMonth.SelectedItem; ;
                    string strLatitutecbx = cbxLatitute.SelectedItem.ToString();
                    tb_solar_radiation_through_glass ro = LibraryManagerInCom.SolarRadiationList.SingleOrDefault(r => r.solar_hour == strSolarHourcbx && r.direction_id == strDirectioncbx && r.month == strMonthcbx && r.latitute == strLatitutecbx);

                    if (ro != null)
                    {

                        txtSolarRadiation.Text = ro.radiation_amount.ToString();
                    }
                }
                catch (Exception)
                {
                    throw;

                }

            }
        }
        //  Load hệ số truyền nhiệt tức thời
        private void loadImmediateEffect()
        {
            if (cbxDirection.SelectedIndex != -1 && cbxPressure.SelectedIndex != -1 && cbxTime.SelectedIndex != -1)
            {


                try
                {

                    int Direction = int.Parse(((tb_glass_direction)cbxDirection.SelectedItem).id.ToString());
                    int Pressure = (int)cbxPressure.SelectedItem;
                    int Time = (int)cbxTime.SelectedItem;
                    tb_immediate_impact im = LibraryManagerInCom.ImmediateImpactList.SingleOrDefault(r => r.direction_id == Direction && r.time == Time && r.weight_per_meter_square == Pressure);
                    if (im != null)
                    {
                        txtImmediate.Text = im.coefficient.ToString();
                    }

                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
        private void cbxLatitute_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxLatitute.SelectedItem != null)
            {
                loadSolarRadition();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxSolarHour_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxSolarHour.SelectedItem != null)
            {
                loadSolarRadition();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxMonth_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxMonth.SelectedItem != null)
            {
                loadSolarRadition();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxDirection_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxDirection.SelectedItem != null)
            {
                loadSolarRadition();
                loadImmediateEffect();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxPressure_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxPressure.SelectedItem != null)
            {
                loadImmediateEffect();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        private void cbxTime_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTime.SelectedItem != null)
            {
                loadImmediateEffect();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        public void enableroof(bool b)
        {
            txtWidthOfRoof.IsEnabled = b;
            txtLengthOfRoof.IsEnabled = b;
            cbxStructureOfRoof.IsEnabled = b;
            cbxCharacteristicsOfRoof.IsEnabled = b;
            txtHeatTransferOfRoof.IsEnabled = b;
            cbxColor.IsEnabled = b;
            cbxTypeOfSurface.IsEnabled = b;
            txtAbsorptionCoefficient.IsEnabled = b;
            lblRoof.IsEnabled = b;
            lblWidthOfRoof.IsEnabled = b;
            lblLengthOfRoof.IsEnabled = b;
            lblStructureOfRoof.IsEnabled = b;
            lblCharacteristicsOfRoof.IsEnabled = b;
            lblHeatTransferOfRoof.IsEnabled = b;
            lblColor.IsEnabled = b;
            lblTypeOfSurface.IsEnabled = b;
            lblAbsorptionCoefficient.IsEnabled = b;
            lblAddRoof.IsEnabled = b;
            lblTagRoof.IsEnabled = b;
            txtTagRoof.IsEnabled = b;
            lstRoof.IsEnabled = b;
            btnDeleteRoof.IsEnabled = b;
            btnCopyRoof.IsEnabled = b;
        }
        public void enableceiling(bool b)
        {
            txtWidthOfCeilling.IsEnabled = b;
            txtLengthOfCeilling.IsEnabled = b;
            cbxStructureOfCeilling.IsEnabled = b;
            cbxCharacteristicsOfCeilling.IsEnabled = b;
            txtHeatTransfer.IsEnabled = b;
            lblCeiling.IsEnabled = b;
            lblWidthOfCeilling.IsEnabled = b;
            lblLengthOfCeilling.IsEnabled = b;
            lblStructureOfCeilling.IsEnabled = b;
            lblCharacteristicsOfCeilling.IsEnabled = b;
            lblHeatTransferOfCeilling.IsEnabled = b;
        }
        //  Check RadioButon ceilling được chọn
        private void radCeilling_Checked(object sender, RoutedEventArgs e)
        {
            btnAddRoof.IsEnabled = false;
            enableceiling(true);
            enableroof(false);
            bSelectedCeiling = true;
            btnApplyConstruction.IsEnabled = true;
        }

        //  Check RadioButoon Roof được chọn
        private void radRoof_Checked(object sender, RoutedEventArgs e)
        {
            bSelectedCeiling = false;
            btnAddRoof.IsEnabled = true;
            enableceiling(false);
            if (lstRoof.Items.Count != 0)
            {
                enableroof(true);
            }
            btnApplyConstruction.IsEnabled = true;
        }
        public void EnableWall(bool b)
        {
            lblWall.IsEnabled = b;
            lblWidthOfWall.IsEnabled = b;
            txtWidthOfWall.IsEnabled = b;
            lblLengthOfWall.IsEnabled = b;
            txtLengthOfWall.IsEnabled = b;
            lblTypeOfExposure.IsEnabled = b;
            cbxTypeOfExposure.IsEnabled = b;
            lblTypeofWall.IsEnabled = b;
            cbxTypeofWall.IsEnabled = b;
            lblHeatResistanceofWall.IsEnabled = b;
            txtHeatResistanceofWall.IsEnabled = b;
            lblAddWall.IsEnabled = b;
            lblTagWall.IsEnabled = b;
            txtTagWall.IsEnabled = b;
            lstWall.IsEnabled = b;
            btnDeleteWall.IsEnabled = b;
            btnCopyWall.IsEnabled = b;
        }

        private void cbxTypeofWall_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxTypeofWall.SelectedItem != null)
            {
                txtHeatResistanceofWall.Text = ((tb_heat_resistance)cbxTypeofWall.SelectedItem).heat_resistance.ToString();
                btnApplyConstruction.IsEnabled = true;
            }
        }

        //  Add wall
        private void btnNewWall_Click(object sender, RoutedEventArgs e)
        {
            EnableWall(true);
            Wall wa = new Wall();
            addWall(wa);
        }

        private void btnDeleteWall_Click(object sender, RoutedEventArgs e)
        {
            room.lConstruction.Remove(wall);
            lstWall.Items.Remove(wall);
            if (lstWall.Items.Count == 0)
            {
                EnableWall(false);
                iWall = 1;
            }
        }

        public void addWall(object o)
        {
            Wall wa = (Wall)o;
            bool overload = false;
            if (txtTagWall.Text != "")
            {
                foreach (object ob in room.lConstruction)
                {
                    if (ob is Wall)
                    {
                        Wall w = (Wall)ob;
                        if (w.sName == txtTagWall.Text)
                        {
                            overload = true;
                            wa.sName = "Wall " + iWall;
                            break;
                        }
                    }
                }
                if (!overload)
                {
                    wa.sName = txtTagWall.Text;
                }
            }
            else
            {
                wa.sName = "Wall " + iWall;
            }
            CheckWallName(wa);
            iWall++;
            room.lConstruction.Add(wa);
            lstWall.Items.Add(wa);
            lstWall.DisplayMemberPath = "sName";
        }

        public void CheckWallName(Wall w)
        {
            foreach (object o in room.lConstruction)
            {
                if (o is Wall)
                {
                    Wall wa = (Wall)o;
                    if (w.sName == wa.sName)
                    {
                        iWall++;
                        w.sName = "Wall " + iWall;
                        CheckWallName(w);
                    }
                }
            }
        }

        private void btnCopyWall_Click(object sender, RoutedEventArgs e)
        {
            if (wall != null)
            {
                Wall wallcopy = (Wall)wall.Clone();
                addWall(wallcopy);
            }
        }

        private void lstWall_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            wall = (Wall)lstWall.SelectedItem;
            if (wall != null)
            {
                txtTagWall.Text = wall.sName;
                txtLengthOfWall.Text = wall.dbLength.ToString();
                txtWidthOfWall.Text = wall.dbWidth.ToString();
                cbxTypeOfExposure.SelectedIndex = wall.iTypeExposure;
                cbxTypeofWall.SelectedIndex = wall.iCharacteristics;
                txtHeatResistanceofWall.Text = wall.dbHeatResistance.ToString();
            }

        }
        private void lstWall_GotFocus(object sender, RoutedEventArgs e)
        {
            updateWall();
        }
        public void updateWall()
        {
            if (wall != null)
            {
                if (txtTagWall.Text != "")
                {
                    wall.sName = txtTagWall.Text;
                }
                wall.dbLength = Convert.ToDouble(txtLengthOfWall.Text);
                wall.dbWidth = Convert.ToDouble(txtWidthOfWall.Text);
                wall.iTypeExposure = cbxTypeOfExposure.SelectedIndex;
                wall.iCharacteristics = cbxTypeofWall.SelectedIndex;
                wall.dbHeatResistance = Convert.ToDouble(txtHeatResistanceofWall.Text);
                room.lConstruction[room.lConstruction.IndexOf(wall)] = wall;
            }
        }
        public void addRoof(object o)
        {
            Roof ro = (Roof)o;
            bool overload = false;
            if (txtTagRoof.Text != "")
            {
                foreach (object ob in room.lConstruction)
                {
                    if (ob is Roof)
                    {
                        Roof r = (Roof)ob;
                        if (r.sName == txtTagRoof.Text)
                        {
                            overload = true;
                            ro.sName = "Roof " + iRoof;
                            break;
                        }
                    }
                }
                if (!overload)
                {
                    ro.sName = txtTagRoof.Text;
                }
            }
            else
            {
                ro.sName = "Roof " + iRoof;
            }
            CheckRoofName(ro);
            iRoof++;
            room.lConstruction.Add(ro);
            lstRoof.Items.Add(ro);
            lstRoof.DisplayMemberPath = "sName";
        }

        public void CheckRoofName(Roof r)
        {
            foreach (object o in room.lConstruction)
            {
                if (o is Roof)
                {
                    Roof ro = (Roof)o;
                    if (r.sName == ro.sName)
                    {
                        iRoof++;
                        r.sName = "Roof " + iRoof;
                        CheckRoofName(r);
                    }
                }
            }
        }

        private void btnAddRoof_Click(object sender, RoutedEventArgs e)
        {
            enableroof(true);
            Roof ro = new Roof();
            addRoof(ro);
        }

        private void btnDeleteRoof_Click(object sender, RoutedEventArgs e)
        {
            room.lConstruction.Remove(roof);
            lstRoof.Items.Remove(roof);
            if (lstRoof.Items.Count == 0)
            {
                enableroof(false);
                iRoof = 1;
            }
        }
        private void btnCopyRoof_Click(object sender, RoutedEventArgs e)
        {
            if (roof != null)
            {
                Roof roofcopy = (Roof)roof.Clone();
                addRoof(roofcopy);
            }
        }


        private void lstRoof_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            roof = (Roof)lstRoof.SelectedItem;
            if (roof != null)
            {
                roof = (Roof)lstRoof.SelectedItem;
                txtTagRoof.Text = roof.sName;
                txtWidthOfRoof.Text = roof.dbWidth.ToString();
                txtLengthOfRoof.Text = roof.dbLength.ToString();
                cbxStructureOfRoof.SelectedIndex = roof.iStructure;
                cbxCharacteristicsOfRoof.SelectedIndex = roof.iCharacteristics;
                txtHeatTransferOfRoof.Text = roof.dbHeatTransferCoefficient.ToString();
                cbxColor.SelectedIndex = roof.iColor;
                cbxTypeOfSurface.SelectedIndex = roof.iSurface;
                txtAbsorptionCoefficient.Text = roof.dbAbsorptionCoefficient.ToString();
            }
        }
        private void lstRoof_GotFocus(object sender, RoutedEventArgs e)
        {
            updateRoof();
        }

        public void updateRoof()
        {
            if (roof != null)
            {
                if (txtTagRoof.Text != "")
                {
                    roof.sName = txtTagRoof.Text;
                }
                roof.dbWidth = Convert.ToDouble(txtWidthOfRoof.Text);
                roof.dbLength = Convert.ToDouble(txtLengthOfRoof.Text);
                roof.iStructure = cbxStructureOfRoof.SelectedIndex;
                roof.iCharacteristics = cbxCharacteristicsOfRoof.SelectedIndex;
                roof.dbHeatTransferCoefficient = Convert.ToDouble(txtHeatTransferOfRoof.Text);
                roof.iColor = cbxColor.SelectedIndex;
                roof.iSurface = cbxTypeOfSurface.SelectedIndex;
                roof.dbThermalRadiation = Convert.ToDouble(txtSolarRadiation.Text);
                roof.dbAbsorptionCoefficient = Convert.ToDouble(txtAbsorptionCoefficient.Text);
                room.lConstruction[room.lConstruction.IndexOf(roof)] = roof;
            }
        }
        //  Apply Roof va Wall
        private void btnApplyConstruction_Click(object sender, RoutedEventArgs e)
        {
            ApplyConstruction();
        }

        public void ApplyConstruction()
        {
            btnApplyConstruction.IsEnabled = false;
            room.gl.iWindowFrameType = cbxTypeOfFrameGlass.SelectedIndex;
            room.gl.dbArea = Convert.ToDouble(txtAreaOfDoor.Text);
            room.gl.iTypeofglass = cbxTypeOfGlass.SelectedIndex;
            room.gl.dbGlassCoefficient = Convert.ToDouble(txtCoefficientOfGlass.Text);
            room.gl.iLatitute = cbxLatitute.SelectedIndex;
            room.gl.iSolarHour = cbxSolarHour.SelectedIndex;
            room.gl.iMonth = cbxMonth.SelectedIndex;
            room.gl.iDirection = cbxDirection.SelectedIndex;
            room.gl.iPressure = cbxPressure.SelectedIndex;
            room.gl.iTime = cbxTime.SelectedIndex;
            room.gl.dbSolarRadition = Convert.ToDouble(txtSolarRadiation.Text);
            room.gl.dbImmediateCoefficient = Convert.ToDouble(txtImmediate.Text);

            if (bSelectedCeiling)
            {
                Ceiling cei = new Ceiling();
                cei.dbWidth = Convert.ToDouble(txtWidthOfCeilling.Text);
                cei.dbLength = Convert.ToDouble(txtLengthOfCeilling.Text);
                cei.iStructure = cbxStructureOfCeilling.SelectedIndex;
                cei.iCharacteristics = cbxCharacteristicsOfCeilling.SelectedIndex;
                cei.dbHeatTransferCoefficient = Convert.ToDouble(txtHeatTransfer.Text);
                bool bNewCeiling = true;
                foreach (Construction c in room.lConstruction)
                {
                    if (c is Ceiling)
                    {
                        room.lConstruction[room.lConstruction.IndexOf(c)] = cei;
                        bNewCeiling = false;
                        break;
                    }
                }
                if (bNewCeiling)
                {
                    room.lConstruction.Add(cei);
                }

                foreach (Roof r in lstRoof.Items)
                {
                    room.lConstruction.Remove(r);
                }
                lstRoof.Items.Clear();
            }
            else
            {
                foreach (Construction c in room.lConstruction)
                {
                    if (c is Ceiling)
                    {
                        room.lConstruction.Remove(c);
                        break;
                    }
                }
                updateRoof();
            }
            updateWall();
            Floor f = new Floor();
            f.dbWidth = Convert.ToDouble(txtWidthOfFloor.Text);
            f.dbLength = Convert.ToDouble(txtLengthOfFloor.Text);
            f.iStructure = cbxStructureOfFloor.SelectedIndex;
            f.iCharacteristics = cbxCharacteristicsOfFloor.SelectedIndex;
            f.dbHeatTransferCoefficient = Convert.ToDouble(txtHeatTransferOfFloor.Text);
            bool bNewFloor = true;
            foreach (Construction c in room.lConstruction)
            {
                if (c is Floor)
                {
                    room.lConstruction[room.lConstruction.IndexOf(c)] = f;
                    bNewFloor = false;
                    break;
                }
            }
            if (bNewFloor)
            {
                room.lConstruction.Add(f);
            }
        }
        #endregion

        #region PROCESS ALTERNATIVE

        public void addAlt(Alternative copyalt)
        {
            altman.AddAlternative(copyalt);
        }

        public void loadAlt(Alternative Alt)
        {
            if (room.sName != null && alt.lRoom.IndexOf(room) != -1)
            {
                if (tabitem.Header != null)
                {
                    if (tabitem.Header.ToString() == "Room")
                    {
                        ApplyRoom();
                    }
                    else
                    {
                        if (tabitem.Header.ToString() == "Internal Load")
                        {
                            ApplyInternalLoad();
                        }
                        else
                        {
                            ApplyConstruction();
                        }
                    }
                }
            }
            alt = Alt;
            if (alt.lRoom.Count == 0)
            {
                iRoom = 1;
            }
            else
            {
                iRoom = alt.lRoom.Count;
            }
            EnableRoom(false);
            btnApplyRoom.IsEnabled = false;
            tabiRoom.IsSelected = true;
        }

        public void deleteAlt()
        {
            altman.DeleteAlternative(alt);
        }

        #endregion

        #region EMPTY VALUE

        public void CheckEmpty(TextBox txt)
        {
            if (txt.Text == "")
            {
                txt.Text = "0";
            }
            if (txt.Text.Contains(' '))
            {
                txt.Text = txt.Text.Remove(txt.Text.IndexOf(' '), 1);
                SystemSounds.Beep.Play();
            }
            if (txt.Text.First() == '.')
            {
                txt.Text = txt.Text.Remove(0, 1);
                SystemSounds.Beep.Play();
            }
        }

        #region for room

        private void txtName_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnApplyRoom.IsEnabled = true;
        }

        private void txtWidthRoom_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtWidthRoom);
            btnApplyRoom.IsEnabled = true;
        }

        private void txtHeighRoom_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtHeighRoom);
            btnApplyRoom.IsEnabled = true;
        }

        private void txtLengthRoom_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtLengthRoom);
            btnApplyRoom.IsEnabled = true;
        }


        private void txtOutsideTemperature_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtOutsideTemperature);
            btnApplyRoom.IsEnabled = true;
        }


        private void txtOutsideAirContainingLevel_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtOutsideAirContainingLevel);
            btnApplyRoom.IsEnabled = true;
        }

        private void txtInsideAirContainingLevel_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtInsideAirContainingLevel);
            btnApplyRoom.IsEnabled = true;
        }
        #endregion

        #region for internal

        private void txtEquipment_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnApplyInternalLoad.IsEnabled = true;
        }

        private void txtNumberOfPeople_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtPeopleDensity);
            btnApplyInternalLoad.IsEnabled = true;
        }

        private void txtPeopleLatentHeat_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtPeopleLatentHeat);
            btnApplyInternalLoad.IsEnabled = true;
        }


        private void txtPeopleSensibleHeat_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtPeopleSensibleHeat);
            btnApplyInternalLoad.IsEnabled = true;
        }

        private void txtAmountAir_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtAmountAir);
            btnApplyInternalLoad.IsEnabled = true;
        }
        #endregion

        #region for construction
        private void txtAreaOfDoor_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtAreaOfDoor);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtCoefficientOfGlass_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtCoefficientOfGlass);
            btnApplyConstruction.IsEnabled = true;
        }


        private void txtSolarRadiation_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtSolarRadiation);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtImmediate_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtImmediate);
            btnApplyConstruction.IsEnabled = true;
        }
        private void txtWidthOfCeilling_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtWidthOfCeilling);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtHeighOfCeilling_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtLengthOfCeilling);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtHeatTransfer_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtHeatTransfer);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtWidthOfRoof_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtWidthOfRoof);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtLengthOfRoof_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtLengthOfRoof);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtAbsorptionCoefficient_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtAbsorptionCoefficient);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtHeatTransferOfRoof_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtHeatTransferOfRoof);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtWidthOfWall_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtWidthOfWall);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtLengthOfWall_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtLengthOfWall);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtWidthOfFloor_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtWidthOfFloor);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtLengthOfFloor_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtLengthOfFloor);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtHeatTransferOfFloor_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtHeatTransferOfFloor);
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtEnergytOfEquipment_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckEmpty(txtEnergytOfEquipment);
            btnApplyInternalLoad.IsEnabled = true;
        }

        private void cbxTypeOfFrameGlass_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtHeatResistanceofWall_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnApplyConstruction.IsEnabled = true;
        }

        private void cbxTypeOfExposure_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnApplyConstruction.IsEnabled = true;
        }

        private void cbxColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnApplyConstruction.IsEnabled = true;
        }

        private void txtTagRoof_TextChanged(object sender, TextChangedEventArgs e)
        {
            btnApplyConstruction.IsEnabled = true;
        }
        #endregion

        #endregion

        #region CHECK INPUT
        private void txtInput_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (Char.IsDigit((Char)e.Text[0]))
            {
                e.Handled = false;
            }
            else
            {
                if ((Char)e.Text[0] == '.')
                {
                    if (!((TextBox)sender).Text.Contains("."))
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                        SystemSounds.Beep.Play();
                    }
                }
                else
                {
                    e.Handled = true;
                    SystemSounds.Beep.Play();
                }
            }
        }
        #endregion

        #region PROCESS TAB CHANGE
        private void tabAirConditioning_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabAirConditioning.SelectedItem != null)
            {
                if (tabitem.Header != null)
                {
                    if (((TabItem)tabAirConditioning.SelectedItem).Header.ToString() != tabitem.Header.ToString())
                    {
                        if (tabitem.Header.ToString() == "Room")
                        {
                            ApplyRoom();
                        }
                        else
                        {
                            if (tabitem.Header.ToString() == "Internal Load")
                            {
                                ApplyInternalLoad();
                            }
                            else
                            {
                                ApplyConstruction();
                            }
                        }
                    }
                }
                tabitem = (TabItem)tabAirConditioning.SelectedItem;
            }
        }

        public void SaveTab()
        {
            if (alt.lRoom.Count != 0)
            {
                if (tabitem.Header.ToString() == "Room")
                {
                    ApplyRoom();
                }
                else
                {
                    if (tabitem.Header.ToString() == "Internal Load")
                    {
                        ApplyInternalLoad();
                    }
                    else
                    {
                        ApplyConstruction();
                    }
                }
            }
        }
        #endregion

        #region GOT FOCUS
        private void txtInput_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            key = txt.Name;
        }

        private void txtInput_Loaded(object sender, RoutedEventArgs e)
        {
            ToolTip tt = new ToolTip();
            TextBox txt = (TextBox)sender;
            ToolTipService.SetPlacement(tt, PlacementMode.Left);
            tt.Content = "Press F1 for Help";
            txt.ToolTip = tt;
        }
        #endregion

        private void grid1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.F1)
            {
                switch (tabitem.Header.ToString())
                {
                    case "Room":
                        System.Windows.Forms.Help.ShowHelp(null, ReferencePath.ReferenceFile, System.Windows.Forms.HelpNavigator.KeywordIndex, RoomScreenReference.ResourceManager.GetString(key));
                        break;
                    case "Internal Load":
                        System.Windows.Forms.Help.ShowHelp(null, ReferencePath.ReferenceFile, System.Windows.Forms.HelpNavigator.KeywordIndex, InternalLoadScreenReference.ResourceManager.GetString(key));
                        break;
                    case "Construction":
                        System.Windows.Forms.Help.ShowHelp(null, ReferencePath.ReferenceFile, System.Windows.Forms.HelpNavigator.KeywordIndex, ConstructionScreenReference.ResourceManager.GetString(key));
                        break;
                }

            }
        }

        public void LoadObject(object obj)
        {
            switch (obj.GetType().Name)
            {
                case "InternalLoad":
                    room.inter = (InternalLoad)obj;
                    break;
                case "Equip":
                    room.inter.lequip.Add((Equip)obj);
                    break;
                case "Glass":
                    room.gl = (Glass)obj;
                    break;
                case "Roof":
                    room.lConstruction.Add((Roof)obj);
                    break;
                case "Wall":
                    room.lConstruction.Add((Wall)obj);
                    break;
                case "Floor":
                    room.lConstruction.Add((Floor)obj);
                    break;
                case "Ceiling":
                    room.lConstruction.Add((Ceiling)obj);
                    break;
            }
        }

        public void SaveProject(XmlTextWriter tw)
        {
            tw.WriteStartElement("AirCondition");
            foreach (Alternative alt in altman.lAlternative)
            {
                tw.WriteStartElement("Alternative");
                foreach (PropertyInfo property in alt.GetType().GetProperties())
                {
                    if (property.GetValue(alt, null) != null)
                    {
                        tw.WriteAttributeString(property.Name, property.GetValue(alt, null).ToString());
                    }
                    else
                    {
                        tw.WriteAttributeString(property.Name, "");
                    }
                }
                foreach (Room r in alt.lRoom)
                {
                    tw.WriteStartElement("Room");
                    foreach (PropertyInfo property in r.GetType().GetProperties())
                    {
                        tw.WriteAttributeString(property.Name, property.GetValue(r, null).ToString());
                    }

                    tw.WriteStartElement("InternalLoad");
                    foreach (PropertyInfo property in r.inter.GetType().GetProperties())
                    {
                        tw.WriteAttributeString(property.Name, property.GetValue(r.inter, null).ToString());
                    }
                    tw.WriteStartElement("EquipmentList");
                    foreach (Equip equip in r.inter.lequip)
                    {
                        tw.WriteStartElement("Equipment");
                        foreach (PropertyInfo property in equip.GetType().GetProperties())
                        {
                            tw.WriteAttributeString(property.Name, property.GetValue(equip, null).ToString());
                        }
                        tw.WriteEndElement();
                    }
                    tw.WriteEndElement();
                    tw.WriteEndElement();

                    tw.WriteStartElement("Glass");
                    foreach (PropertyInfo property in r.gl.GetType().GetProperties())
                    {
                        tw.WriteAttributeString(property.Name, property.GetValue(r.gl, null).ToString());
                    }
                    tw.WriteEndElement();

                    tw.WriteStartElement("Construction");
                    foreach (Construction con in r.lConstruction)
                    {
                        tw.WriteStartElement(con.GetType().Name);
                        foreach (PropertyInfo property in con.GetType().GetProperties())
                        {
                            if (property.GetValue(con, null) != null)
                            {
                                tw.WriteAttributeString(property.Name, property.GetValue(con, null).ToString());
                            }
                            else
                            {
                                tw.WriteAttributeString(property.Name, "");
                            }
                        }
                        tw.WriteEndElement();
                    }
                    tw.WriteEndElement();

                    tw.WriteEndElement();
                }
                tw.WriteEndElement();
            }

            tw.WriteEndElement();
        }

        public object GetResult()
        {
            return altman.lAlternative;
        }

    }
}

